﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;

namespace RealIce.Server.Data.RealIce.NHibernate
{
    public static class NHibernate
    {
        private static ISessionFactory mySessionFactory;
        private static ISession myCurrentSession;
        private static Configuration myConfiguration;
        //private static ISessionFactory mySessionFactory;
        //private static ISession myCurrentSession;
        //private static Configuration myConfiguration;
        /// <summary>
        /// Creates an NHibernate ISessionFactory with the specified configuration in web.config
        /// </summary>
        static NHibernate()
        {
                myConfiguration = new Configuration();
                //TODO cambiar la ruta a una dinamica
                myConfiguration.Configure("c:\\hibernate.cfg.xml");
                mySessionFactory = myConfiguration.BuildSessionFactory();
        }

        /// <summary>
        /// Method that creates an ISession from the ISession factory if was not created
        /// early, otherwise it returns the current ISession
        /// </summary>
        /// <returns>Return the current ISession</returns>
        public static ISession GetCurrentSession()
        {
            if (myCurrentSession == null)
            {
                myCurrentSession = mySessionFactory.OpenSession();
            }

            if ((myCurrentSession != null) && (myCurrentSession.IsOpen == false))
            {
                myCurrentSession = mySessionFactory.OpenSession();
            }

            return myCurrentSession;
        }

        /// <summary>
        /// Method to close the current ISession
        /// </summary> 

        public static bool CloseSession()
        {
            if (myCurrentSession != null)
            {
                if (myCurrentSession.IsOpen)
                {
                    myCurrentSession.Close();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Method to close the ISessionFactory
        /// </summary>
        /// 
        public static void CloseSessionFactory()
        {
            if (mySessionFactory != null)
                mySessionFactory.Close();
        }
    }
}
